package com.rainbow.security

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.rainbow.common.RespBean
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.web.access.AccessDeniedHandler
import org.springframework.stereotype.Component
import java.io.PrintWriter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class AuthenticationAccessDeniedHandler : AccessDeniedHandler {

    val objectMapper by lazy { ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)!! }

    override fun handle(request: HttpServletRequest, response: HttpServletResponse, e: AccessDeniedException) {
        response.status = HttpServletResponse.SC_FORBIDDEN
        response.contentType = "application/json;charset=UTF-8"

        val out: PrintWriter = response.writer

        val error = RespBean.error("权限不足，请联系管理员!")

        out.write(objectMapper.writeValueAsString(error))

        out.flush()
        out.close()
    }
}